let allMusic = [
    {
        name: "小幸运",
        artist: "田馥甄",
        img: "music-1",
        src: "music-1"
    },
    {
        name: "大城小爱",
        artist: "王力宏",
        img: "music-2",
        src: "music-2"
    },
    {
        name: "年少有为",
        artist: "李荣浩",
        img: "music-3",
        src: "music-3"
    },
    {
        name: "一千年以后",
        artist: "林俊杰",
        img: "music-4",
        src: "music-4"
    },
    {
        name: "下一秒",
        artist: "张碧晨",
        img: "music-5",
        src: "music-5"
    }
]

const wrapper = document.querySelector(".wrapper"),
    musicImg = wrapper.querySelector(".img-area img"),
    musicName = wrapper.querySelector(".song-details .name"),
    musicArtist = wrapper.querySelector(".song-details .artist"),
    mainAudio = wrapper.querySelector("#main-audio"),
    playPauseBtn = wrapper.querySelector(".paly-pause"),
    prevBtn = wrapper.querySelector(".icon-shangyiqu"),
    nextBtn = wrapper.querySelector(".icon-xiayiqu"),
    progressArea = wrapper.querySelector('.progress-area'),
    progressBar = wrapper.querySelector('.progress-bar'),
    showMoreBtn = wrapper.querySelector('#more-music'),
    musicList = wrapper.querySelector(".music-list"),
    hideMusicBtn = musicList.querySelector('.icon-cuowu')

showMoreBtn.addEventListener("click", () => {
    musicList.classList.toggle("show")
})

hideMusicBtn.addEventListener("click", () => {
    showMoreBtn.click()
})

let musicIndex = 2;
window.addEventListener('load', () => {
    loadMusic(musicIndex)
})
function loadMusic(indexNumb) {
    musicName.innerText = allMusic[indexNumb - 1].name
    musicArtist.innerText = allMusic[indexNumb - 1].artist
    musicImg.src = `img/${allMusic[indexNumb - 1].img}.jpg`
    mainAudio.src = `songs/${allMusic[indexNumb - 1].src}.mp3`
}
function nextMusic() {
    musicIndex++;
    musicIndex > allMusic.length ? musicIndex = 1 : musicIndex = musicIndex
    loadMusic(musicIndex)
    playMusic();
}
function prevMusic() {
    musicIndex--;
    musicIndex < 1 ? musicIndex = allMusic.length : musicIndex = musicIndex
    loadMusic(musicIndex)
    playMusic();
}
function playMusic() {
    wrapper.classList.add("paused")

    mainAudio.play()
}
function pauseMusic() {
    wrapper.classList.remove("paused")

    mainAudio.pause()
}

playPauseBtn.addEventListener('click', () => {
    const isMusicPaused = wrapper.classList.contains('paused');
    isMusicPaused ? pauseMusic() : playMusic();

});

nextBtn.addEventListener('click', () => {
    nextMusic();
});
prevBtn.addEventListener('click', () => {
    prevMusic()
})
// timeupdate 事件
// 在音频/视频（audio/video）的播放位置发生改变时触发。
mainAudio.addEventListener("timeupdate", (e) => {
    //   console.log(e);
    //我们要开始时间和持续时间
    const currentTime = e.target.currentTime
    const duration = e.target.duration
    let progressWidth = (currentTime / duration) * 100;
    progressBar.style.width = `${progressWidth}%`
    let musicCurrentTime = wrapper.querySelector(".current"),
        musicDuration = wrapper.querySelector(".duration")

    mainAudio.addEventListener("loadeddata", () => {


        // 得到音乐总时长
        let audioDuration = mainAudio.duration
        // 计算得到分钟
        let totalMin = Math.floor(audioDuration / 60);
        // 计算得到秒钟，不断对60取余数，不足60s的就是最终的秒钟
        let totalSec = Math.floor(audioDuration % 60);
        // 不足10s补0
        if (totalSec < 10) {
            totalSec = `0${totalSec}`;
        }
        musicDuration.innerText = `${totalMin}:${totalSec}`;


    })
    let currentMin = Math.floor(currentTime / 60);
    let currentSec = Math.floor(currentTime % 60);
    if (currentSec < 10) {
        currentSec = `0${currentSec}`;
    }
    musicCurrentTime.innerText = `${currentMin}:${currentSec}`;

})

// 点击进度条容器触发的事件（因为进度条的长度是变化所以不能使用进度条）
progressArea.addEventListener('click', e => {
    // 得到进度条的宽度
    let progressWidthval = progressArea.clientWidth;
    // 得到点击位置的x坐标（相对于进度条）
    let clickedOffSetX = e.offsetX;
    //   得到播放总时长
    let songDuration = mainAudio.duration;

    //  改变当前的时间
    mainAudio.currentTime = (clickedOffSetX / progressWidthval) * songDuration;
    playMusic();
});

const ulTag = wrapper.querySelector("ul")
for (let i = 0; i < allMusic.length; i++) {
    const liTag = ` <li li-index="${i+1}">
     <div class="row">
         <span>${allMusic[i].name} &nbsp; ${allMusic[i].artist}</span>
  
     </div>
     <audio class="${allMusic[i].src}" src="songs/${allMusic[i].src}.mp3"></audio>
     <span id="${allMusic[i].src}" class="audio-duration">3:40</span>
 </li>`
//  添加HTML内容与文本内容以前用的是innerHTML与innerText方法，

// 最近发现还有insertAdjacentHTML和 insertAdjacentText方法，

// 这两个方法更灵活，可以在指定的地方插入html内容和文本内容
// 有四种值可用：

// 1.     beforeBegin: 插入到标签开始前

// 2.     afterBegin:插入到标签开始标记之后

// 3.     beforeEnd:插入到标签结束标记前

// 4.     afterEnd:插入到标签结束标记后
 ulTag.insertAdjacentHTML("beforeend",liTag)
 let liAudioDuaration=ulTag.querySelector(`#${allMusic[i].src}`)
 let liAudioTag=ulTag.querySelector(`.${allMusic[i].src}`)
// loadeddata事件用于在不播放的情况下获取音频总持续时间
 liAudioTag.addEventListener("loadeddata",()=>{
      // 得到音乐总时长
      let audioDuration = liAudioTag.duration
      // 计算得到分钟
      let totalMin = Math.floor(audioDuration / 60);
      // 计算得到秒钟，不断对60取余数，不足60s的就是最终的秒钟
      let totalSec = Math.floor(audioDuration % 60);
      // 不足10s补0
      if (totalSec < 10) {
          totalSec = `0${totalSec}`;
      }
      liAudioDuaration.innerText = `${totalMin}:${totalSec}`;
 })
}
 const allLiTags=ulTag.querySelectorAll("li")
 for (let index = 0; index < allLiTags.length; index++) {
    
    allLiTags[index].setAttribute('onclick', 'clicked(this)')
     
 }


function clicked(element){
    let getLiIndex=element.getAttribute("li-index")
    musicIndex=getLiIndex
    loadMusic(musicIndex)
    playMusic()
}
